<template>
  <div class="admin-manager-container">
    <!-- 搜索栏（保持与其它模块一致） -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.query" placeholder="用户名关键字" style="width:180px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-card">
      <el-table :data="displayedData" :loading="tableLoading" border style="width: 100%" size="small">
        <el-table-column type="index" label="序号" width="60" align="center" fixed="left" />
        <el-table-column prop="admin_id" label="管理员编号" width="120" align="center" />
        <el-table-column prop="admin_username" label="用户名" :min-width="200" show-overflow-tooltip />
        <el-table-column prop="role_name" label="角色" width="140">
          <template #default="{ row }">
            <span class="badge badge--blue">{{ row.role_name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rights_count" label="权限数量" width="120" align="center">
          <template #default="{ row }">
            <span class="badge badge--red">{{ row.rights_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" :icon="DeleteIcon" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="400px"
      class="form-dialog"
      modal-class="light-modal-mask"
    >
      <el-form :model="dialogForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="dialogForm.admin_username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="dialogForm.admin_password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="dialogForm.role_id" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :key="item.role_id"
              :label="item.role_name"
              :value="item.role_id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 自定义删除确认弹窗 -->
    <BaseConfirmDialog
      :visible="confirmVisible"
      title="提示"
      :message="confirmMessage"
      confirm-text="确定"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="confirmVisible=false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getAdminAPI, addAdminAPI, updateAdminAPI, deleteAdminAPI } from '@/api/admin/admin.js'
import { getRoleAPI } from '@/api/authApi.js' // Assuming you have this api for roles
import { ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete as DeleteIcon, Search, Refresh } from '@element-plus/icons-vue'
import { computed } from 'vue'
import BaseConfirmDialog from '@/components/BaseConfirmDialog.vue'

// 表格数据
const tableData = ref([])
const searchForm = reactive({ query: '' })
const displayedData = computed(() => {
  const q = searchForm.query.trim().toLowerCase()
  if (!q) return tableData.value
  return tableData.value.filter(
    (row) =>
      String(row.admin_username || '').toLowerCase().includes(q) ||
      String(row.role_name || '').toLowerCase().includes(q)
  )
})
const tableLoading = ref(false)

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogForm = reactive({
  admin_id: '',
  admin_username: '',
  admin_password: '',
  role_id: ''
})
const isEdit = ref(false)

// 角色下拉列表
const roleList = ref([])

// 获取管理员数据
const fetchAdmins = async () => {
  tableLoading.value = true
  try {
    const res = await getAdminAPI()
    tableData.value = res || []
  } finally {
    tableLoading.value = false
  }
}

// 获取角色数据
const fetchRoles = async () => {
  const res = await getRoleAPI()
  roleList.value = res || []
}

onMounted(() => {
  fetchAdmins()
  fetchRoles()
})

const handleSearch = () => {}
const handleReset = () => {
  searchForm.query = ''
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加管理员'
  Object.assign(dialogForm, {
    admin_id: '',
    admin_username: '',
    admin_password: '',
    role_id: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑管理员'
  Object.assign(dialogForm, row)
  dialogForm.admin_password = '' // Do not show password
  dialogVisible.value = true
}

// 删除
const confirmVisible = ref(false)
const confirmMessage = ref('')
let pendingDeleteId = ''
const handleDelete = (row) => {
  pendingDeleteId = row.admin_id
  confirmMessage.value = `确定要删除管理员 "${row.admin_username}" 吗？`
  confirmVisible.value = true
}
const confirmDelete = async () => {
  await deleteAdminAPI({ admin_id: pendingDeleteId })
  confirmVisible.value = false
  fetchAdmins()
}

// 提交表单
const handleSubmit = async () => {
  let res
  const payload = { ...dialogForm }
  if (!payload.admin_password) {
    delete payload.admin_password // Don't send empty password
  }

  if (isEdit.value) {
    res = await updateAdminAPI(payload)
  } else {
    res = await addAdminAPI(payload)
  }
  dialogVisible.value = false
  fetchAdmins()
}
</script>

<style lang="scss" scoped>

.admin-manager-container {
  padding: 8px 20px 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.search-bar { display:flex; align-items:center; padding:0; margin:0 0 18px 0; background:none; border:none; box-shadow:none; }
.search-form { display:flex; align-items:center; gap:0; padding:0; margin:0; }
.search-form .el-form-item { margin-bottom:0; margin-right:8px; }
.search-form .el-input__wrapper, .search-form .el-button { height:26px !important; min-height:26px !important; font-size:13px; }
.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 0 12px 0;
}
.header-row .title {
  font-size: 16px;
  font-weight: 600;
}
.header-row .ops {
  display: flex;
  align-items: center;
  gap: 8px;
}
.table-card {
  margin-top: 0;
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.el-table {
  margin-top: 0;
}
.el-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: flex-start;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
</style>
